package com.learn.yh.aws;

import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
import com.zaxxer.hikari.HikariDataSource;
import com.zaxxer.hikari.pool.HikariPool;
import com.zaxxer.hikari.util.DriverDataSource;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.util.Set;

/**
 * @author: Yh
 * @date: 2021/4/15 16:13
 */
@Component
public class DataSourceHandler implements ApplicationRunner {

    private final ApplicationContext applicationContext;

    public DataSourceHandler(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }


    @Override
    public void run(ApplicationArguments args) throws Exception {
        DynamicRoutingDataSource cast = DynamicRoutingDataSource.class.cast(applicationContext.getBean("dataSource"));
        Set<String> strings = cast.getCurrentDataSources().keySet();
        for (String string : strings) {
            HikariDataSource dataSource = (HikariDataSource) cast.getDataSource(string);
            HikariPool hikariPoolMXBean = (HikariPool) dataSource.getHikariPoolMXBean();
            hikariPoolMXBean.softEvictConnections();
            try {
                Field dataSourceField = HikariPool.class.getSuperclass().getDeclaredField("dataSource");
                dataSourceField.setAccessible(true);
                Object o1 = dataSourceField.get(hikariPoolMXBean);
                if (o1.getClass() == IDriverDataSource.class) {
                    continue;
                }
                //在此处植入 aws的密码获取
                dataSourceField.set(hikariPoolMXBean, new IDriverDataSource((DriverDataSource) o1));
                Object o = dataSourceField.get(hikariPoolMXBean);
                System.out.println(o.getClass());
            } catch (IllegalAccessException | NoSuchFieldException e) {
                e.printStackTrace();
            }
        }
    }
}